<?php

declare(strict_types=1);

namespace App\Robot\Job;

use App\Common\Robot\Robot;
use App\CustHub\Constants\RoomInviteAcceptStatusConstants;
use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Model\ChRoomInviteAcceptConfig;
use App\CustHub\Model\ChRoomInviteAcceptRecord;
use App\CustHub\Service\ChRoomInviteAcceptConfigService;
use Hyperf\AsyncQueue\Job;

class RoomInviteAcceptJob extends Job
{
    public array $data;

    /**
     * 任务执行失败后的重试次数，即最大执行次数为 $maxAttempts+1 次
     */
    protected int $maxAttempts = 2;

    public function __construct(array $data)
    {
        $this->data = $data;
    }

    public function handle()
    {
        try {
            $recordId = $this->data['recordId'];
            $recordInfo = ChRoomInviteAcceptRecord::query()
                ->where('id',$recordId)
                ->first();
            if(empty($recordInfo)){
                return;
            }

            $inviteData =$recordInfo->invite_data;

            $robot = container()->get(ChRobotMapper::class)->findById($recordInfo->robot_id);

            $robotApi = make(Robot::class,[$robot->server_id,$robot->uuid])->gateway();
            $rst = $robotApi->confirmInvitedMemberList($recordInfo->room_id,$inviteData['inviter_id'],(string)$inviteData['invite_msg_server_id'],$inviteData['invite_code'],$inviteData['invited_member_list']);

            $reason = '';
            if($rst !== false){
                container()->get(ChRoomInviteAcceptConfigService::class)->incAcceptTodayInviteCount($recordInfo->config_id);
                ChRoomInviteAcceptConfig::query()
                    ->where('id',$recordInfo->config_id)
                    ->increment('accept_total');
                $status = RoomInviteAcceptStatusConstants::STATUS_SUCCESS;
            }else{
                $reason = $robotApi->getErrorMsg();
                $status = RoomInviteAcceptStatusConstants::STATUS_FAIL;
            }

            ChRoomInviteAcceptRecord::query()
                ->where('id',$recordId)
                ->update(['status' => $status,'reason' => $reason]);
        }catch (\Throwable $e){
            logger()->info('接受群邀请任务执行失败'.$recordId.'失败原因'.$e->getMessage());
        }
    }

}